
"""
Utility methods for the pygame ui.
"""


import pygame
import os

main_dir = os.path.split(os.path.abspath(__file__))[0]
image_dir = os.path.join(main_dir, 'image')


class ColorSpectrum:
    """
    Class that returns a identifying color for a value in a spectrum of
    values between a min and max value.
    """
    def __init__(self, low = 0, high = 100, invert = False):
        """
        low - The minimum value in the spectrum of possible values
        high - The maximum value in the spectrum of possible values
        invert - Set to true if high values should be green and low values
                 should be zero
        """
        self.low = low
        self.high = high
        self.range = self.high - self.low
        self.invert = invert
    
        
    def get_color(self, value):
        """
        Returns the color that represents the given value.  If the value is
        lower than the min then the color returned is the same as if the min was
        entered as the value.  If the value is higher than the max then the
        color returned is the same as if max was entered as the value.
        
        The colors are generated by generating green for the minimum and red
        for the maximum.  Colors inbetween are determined by adding
        progressively more red to a full (255) green color until red has also
        reached 255 (giving yellow).  Then the green value is reduced to zero as
        the value reaches the maximum, leaving solid red.
        
        value - The value to get a color for
        """
        value = min(value, self.high)
        value = max(value, self.low)
        norm = 0
        if self.invert: norm = self.high - value
        else: norm = value - self.low
        
        # mid is used to determine when the color has reached the middle color
        # i.e. 255 green and 255 red.  Note is not halfway inbetween since
        # changes in greens are much harder to percieve
        mid = int((self.range + 1) / 3)
        
        #Determine the red color component
        r  = int(255 * norm / mid)
        r  = min(r, 255)
        
        #Determine the green color component
        g  = int(255 - 255 * (norm - mid) / (self.range - mid))
        g  = min(g, 255)
        
        return (r, g, 0)
        

def load_image(name, colorkey=None):
    fullname = os.path.join(image_dir, name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error:
        print ('Cannot load image:', fullname)
        raise SystemExit(str(geterror()))
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()
    


